﻿using FastDFSCore;
using FileStorageCenter.Services;
using FileStorageCenter.Services.FileStorageProvider;
using FileStorageCenter.Services.FileStorageProvider.FastDFS;
using FileStorageCenter.Services.Models;
using FileStorageCenter.Services.Services;
using FileStorageCenter.Services.Services.Impl;
using HelenServer.Modules.FileStorage.Abstractions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Configuration;

namespace Microsoft.Extensions.DependencyInjection;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddApplicationServices(this IServiceCollection services)
    {
        services.AddScoped<IFileInfoService, FileInfoService>();
        services.AddScoped<IUserService, UserService>();

        services.AddScoped<IFileStorageProvider, FastDFSProvider>();
        services.AddScoped<IFileStorageService, FileStorageService>();

        services.AddSingleton<IActionResultExecutor<BpctFileStreamResult>, BpctFileStreamResultExecutor>();

        return services;
    }

    public static IServiceCollection AddDistributedFileStorage(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddFastDFSCore(cfg =>
        {
            var config = configuration.GetSection("FastDFS");
            var name = config.GetValue<string>("name");
            var trackers = new List<Tracker>()
            {
                new Tracker
                {
                    IPAddress = config.GetSection("IPAddress").Value,
                    Port = int.Parse(config.GetSection("Port").Value)
                }
            };

            cfg.ClusterConfigurations.Add(new ClusterConfiguration
            {
                Name = name,
                Trackers = trackers,
            });
        }).AddFastDFSDotNetty();

        services.AddOptions<FastDFSContainerOptions>()
            .Configure<IConfiguration>((opts, cfg) =>
            {
                cfg.Bind(FastDFSContainerOptions.Position, opts);
            });

        services.AddSingleton<IUploadQueueProvider<UploadModel>, UploadQueueProvider>();

        services.AddHostedService<UploadHostedService>();

        return services;
    }
}